namespace SinaFinance.CtrlDelegate
{
    using SinaFinanceBaseClassLibrary;
    using System;
    using System.Linq;
    using System.Windows.Threading;
    using System.Xml.Linq;

    public static class IntervalUpdates
    {
        private static DispatcherTimer baseInfoTimerUpdate = new DispatcherTimer();
        public static DB_RealTime db_rt;
        private static XDocument doc = XDocument.Load("PageConfig.xml");
        public static PostResourceDelegate itvlPostRscDelegate;
        public static UpdateBaseInfoDelegate itvlUpdatesDelegate;
        private static DispatcherTimer topViewTimerUpdate = new DispatcherTimer();
        public static string ts_IntervalTime = "09:30";

        static IntervalUpdates()
        {
            XElement element = (from labels in doc.Elements("Configs").Elements<XElement>("BaseInfoArea").Elements<XElement>("IntervalSetting") select labels).ToList<XElement>()[0];
            baseInfoTimerUpdate.Interval = new TimeSpan(0, 0, (int) element.Element("TimeSpan"));
            baseInfoTimerUpdate.Tick += new EventHandler(IntervalUpdates.timerUpdate_Tick);
        }

        public static void IntervalRscDelegate()
        {
            if (db_rt != null)
            {
                itvlPostRscDelegate(db_rt);
            }
        }

        public static void SetDelegate(UpdateBaseInfoDelegate ctrlUpdateDel)
        {
            itvlUpdatesDelegate = (UpdateBaseInfoDelegate) Delegate.Combine((Delegate) itvlUpdatesDelegate, (Delegate) ctrlUpdateDel);
        }

        public static void SetRscDelegate(PostResourceDelegate ctrlRscDel)
        {
            itvlPostRscDelegate = ctrlRscDel;
        }

        public static void Start()
        {
            baseInfoTimerUpdate.Start();
        }

        public static void Stop()
        {
            baseInfoTimerUpdate.Stop();
        }

        private static void timerUpdate_Tick(object sender, EventArgs e)
        {
            if ((itvlUpdatesDelegate != null) && (((DateTime.Now.TimeOfDay >= TimeSpan.Parse("9:31")) && (DateTime.Now.TimeOfDay <= TimeSpan.Parse("11:30"))) || ((DateTime.Now.TimeOfDay >= TimeSpan.Parse("13:00")) && (DateTime.Now.TimeOfDay <= TimeSpan.Parse("15:00")))))
            {
                itvlUpdatesDelegate();
            }
        }
    }
}
